import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { LoadingManager, LOADING_KEYS } from '../utils/loadingManager'
import { ROLES } from '../constants/roleConstants'

const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Demo = () => import('../views/Demo.vue')
const TicketSubmit = () => import('../views/TicketSubmit.vue')
const TicketList = () => import('../views/TicketList.vue')
const TicketDetail = () => import('../views/TicketDetail.vue')
const TicketManagement = () => import('../views/TicketManagement.vue')
const SystemSettings = () => import('../views/SystemSettings.vue')
const UserManagement = () => import('../views/UserManagement.vue')
const Reports = () => import('../views/Reports.vue')
const Notifications = () => import('../views/Notifications.vue')
const FileManagement = () => import('../views/FileManagement.vue')
const PersonalCenter = () => import('../views/PersonalCenter.vue')
const NotFound = () => import('../views/NotFound.vue')
const RoleManagement = () => import('../views/RoleManagement.vue')
const PermissionDemo = () => import('../views/PermissionDemo.vue')
const StatisticsDashboard = () => import('../components/StatisticsDashboard.vue')

const routes = [
  { 
    path: '/', 
    redirect: '/dashboard' 
  },
  { 
    path: '/login', 
    name: 'Login', 
    component: Login,
    meta: { 
      requiresAuth: false,
      title: '登录'
    }
  },
  { 
    path: '/register', 
    name: 'Register', 
    component: Register,
    meta: { 
      requiresAuth: false,
      title: '注册'
    }
  },
  { 
    path: '/dashboard', 
    name: 'Dashboard', 
    component: Dashboard,
    meta: { 
      requiresAuth: true,
      title: '仪表板',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/demo', 
    name: 'DemoPage', 
    component: Demo,
    meta: { 
      requiresAuth: true,
      title: '演示页面',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/submit', 
    name: 'TicketSubmit', 
    component: TicketSubmit,
    meta: { 
      requiresAuth: true,
      title: '提交工单',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/tickets', 
    name: 'TicketList', 
    component: TicketList,
    meta: { 
      requiresAuth: true,
      title: '工单列表',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/tickets/:id', 
    name: 'TicketDetail', 
    component: TicketDetail, 
    props: true,
    meta: { 
      requiresAuth: true,
      title: '工单详情',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/ticket-management', 
    name: 'TicketManagement', 
    component: TicketManagement,
    meta: { 
      requiresAuth: true,
      title: '工单管理',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.SUPERVISOR],
      permissions: ['ticket:assign']
    }
  },
  { 
    path: '/system-settings', 
    name: 'SystemSettings', 
    component: SystemSettings,
    meta: { 
      requiresAuth: true,
      title: '系统设置',
      roles: [ROLES.ADMIN],
      permissions: ['system:config']
    }
  },
  { 
    path: '/user-management', 
    name: 'UserManagement', 
    component: UserManagement,
    meta: { 
      requiresAuth: true,
      title: '用户管理',
      roles: [ROLES.ADMIN, ROLES.SUPERVISOR],
      permissions: ['user:manage']
    }
  },
  { 
    path: '/reports', 
    name: 'Reports', 
    component: Reports,
    meta: { 
      requiresAuth: true,
      title: '报表中心',
      roles: [ROLES.ADMIN, ROLES.SUPERVISOR, ROLES.AGENT],
      permissions: ['report:view']
    }
  },
  { 
    path: '/statistics-dashboard', 
    name: 'StatisticsDashboard', 
    component: StatisticsDashboard,
    meta: { 
      requiresAuth: true,
      title: '统计报表',
      roles: [ROLES.ADMIN, ROLES.SUPERVISOR, ROLES.AGENT],
      permissions: ['report:view']
    }
  },
  { 
    path: '/notifications', 
    name: 'Notifications', 
    component: Notifications,
    meta: { 
      requiresAuth: true,
      title: '通知中心',
      roles: [ROLES.ADMIN, ROLES.SUPERVISOR, ROLES.AGENT],
      permissions: ['notification:manage']
    }
  },
  { 
    path: '/file-management', 
    name: 'FileManagement', 
    component: FileManagement,
    meta: { 
      requiresAuth: true,
      title: '文件管理',
      roles: [ROLES.ADMIN, ROLES.SUPERVISOR, ROLES.AGENT],
      permissions: ['file:manage']
    }
  },
  { 
    path: '/personal-center', 
    name: 'PersonalCenter', 
    component: PersonalCenter,
    meta: { 
      requiresAuth: true,
      title: '个人中心',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/role-management', 
    name: 'RoleManagement', 
    component: RoleManagement,
    meta: { 
      requiresAuth: true,
      title: '角色管理',
      roles: [ROLES.ADMIN],
      permissions: ['user:manage']
    }
  },
  { 
    path: '/permission-demo', 
    name: 'PermissionDemo', 
    component: PermissionDemo,
    meta: { 
      requiresAuth: true,
      title: '权限演示',
      roles: [ROLES.ADMIN, ROLES.AGENT, ROLES.CUSTOMER, ROLES.SUPERVISOR]
    }
  },
  { 
    path: '/403', 
    name: 'Forbidden', 
    component: () => import('../views/Forbidden.vue'),
    meta: { 
      requiresAuth: true,
      title: '访问被拒绝'
    }
  },
  { 
    path: '/:pathMatch(.*)*', 
    name: 'NotFound', 
    component: NotFound,
    meta: { 
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 权限验证缓存（缓存路由权限检查结果）
const permissionCheckCache = new Map()
const CACHE_TTL = 2 * 60 * 1000  // 缓存2分钟

/**
 * 检查权限缓存是否有效
 * @param {string} key - 缓存键
 * @returns {boolean|null}
 */
function getCachedPermissionCheck(key) {
  const cached = permissionCheckCache.get(key)
  if (!cached) return null
  
  const now = Date.now()
  if (now - cached.timestamp > CACHE_TTL) {
    permissionCheckCache.delete(key)
    return null
  }
  
  return cached.result
}

/**
 * 缓存权限检查结果
 * @param {string} key - 缓存键
 * @param {boolean} result - 检查结果
 */
function cachePermissionCheck(key, result) {
  permissionCheckCache.set(key, {
    result,
    timestamp: Date.now()
  })
}

/**
 * 清除所有权限缓存
 */
function clearPermissionCache() {
  permissionCheckCache.clear()
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始路由加载
  LoadingManager.startLoading(LOADING_KEYS.ROUTE_LOADING, {
    message: '加载页面中...',
    timeout: 10000
  })
  
  const authStore = useAuthStore()
  
  console.log('🔍 路由守卫检查:', {
    to: to.path,
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    roles: to.meta.roles,
    permissions: to.meta.permissions
  })
  
  try {
    // 初始化认证状态
    if (!authStore.isAuthenticated) {
      const initResult = authStore.initAuth()
      console.log('🔍 认证状态初始化结果:', initResult)
      
      // 初始化后加载权限申请记录
      if (initResult) {
        authStore.loadPermissionRequests()
      }
    } else {
      // 即使已认证，也要验证token有效性
      const { AuthService } = await import('../services/auth')
      if (!AuthService.isTokenValid()) {
        console.log('⚠️ Token已过期，重新初始化认证状态')
        authStore.logout()
        const initResult = authStore.initAuth()
        
        // 如果初始化后仍未认证，且需要认证才能访问，则跳转登录页
        if (!initResult && to.meta.requiresAuth) {
          LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
          return
        }
      }
    }
    
    // 检查是否需要认证
    if (to.meta.requiresAuth && !authStore.isAuthenticated) {
      console.log('❌ 需要认证但未登录，重定向到登录页')
      LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
      next({
        path: '/login',
        query: { redirect: to.fullPath }  // 记录目标路径，登录后可以重定向
      })
      return
    }
    
    // 已登录用户访问登录/注册页面，重定向到仪表板
    if ((to.path === '/login' || to.path === '/register') && authStore.isAuthenticated) {
      console.log('✅ 已登录用户访问登录页，重定向到仪表板')
      LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
      
      // 如果有redirect参数，则重定向到目标页面
      const redirect = from.query.redirect || '/dashboard'
      next(redirect)
      return
    }
    
    // 如果不需要认证，直接通过
    if (!to.meta.requiresAuth) {
      console.log('✅ 页面不需要认证，直接通过')
      LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
      next()
      return
    }
    
    // ========== 权限验证 ==========
    
    // 生成缓存键
    const cacheKey = `${to.path}_${authStore.role}_${authStore.permissions.join(',')}`
    const cachedResult = getCachedPermissionCheck(cacheKey)
    
    if (cachedResult !== null) {
      console.log('✅ 使用缓存的权限检查结果')
      if (cachedResult) {
        LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
        next()
      } else {
        LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
        next('/403')
      }
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && to.meta.roles.length > 0) {
      const hasRoleAccess = to.meta.roles.includes(authStore.role)
      console.log('🔍 角色权限检查:', {
        requiredRoles: to.meta.roles,
        userRole: authStore.role,
        hasAccess: hasRoleAccess
      })
      
      if (!hasRoleAccess) {
        console.log('❌ 角色权限不足，重定向到403页面')
        
        // 记录权限错误
        authStore.setPermissionError({
          type: 'ROLE_INSUFFICIENT',
          requiredRoles: to.meta.roles,
          userRole: authStore.role,
          targetPath: to.path,
          timestamp: new Date().toISOString()
        })
        
        // 缓存结果
        cachePermissionCheck(cacheKey, false)
        
        LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
        next({
          path: '/403',
          query: {
            reason: 'ROLE_INSUFFICIENT',
            required: JSON.stringify(to.meta.roles),
            current: authStore.role,
            from: to.path,
            title: to.meta.title || '未知页面',
            canRefresh: 'true'  // 标记可以尝试刷新权限
          }
        })
        return
      }
    }
    
    // 检查具体权限
    if (to.meta.permissions && to.meta.permissions.length > 0) {
      const hasPermission = to.meta.permissions.some(permission => 
        authStore.hasPermission(permission)
      )
      console.log('🔍 功能权限检查:', {
        requiredPermissions: to.meta.permissions,
        userPermissions: authStore.permissions,
        hasAccess: hasPermission
      })
      
      if (!hasPermission) {
        console.log('❌ 功能权限不足，重定向到403页面')
        
        // 记录权限错误
        authStore.setPermissionError({
          type: 'PERMISSION_DENIED',
          requiredPermissions: to.meta.permissions,
          userPermissions: authStore.permissions,
          targetPath: to.path,
          timestamp: new Date().toISOString()
        })
        
        // 缓存结果
        cachePermissionCheck(cacheKey, false)
        
        LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
        next({
          path: '/403',
          query: {
            reason: 'PERMISSION_DENIED',
            required: JSON.stringify(to.meta.permissions),
            current: JSON.stringify(authStore.permissions),
            from: to.path,
            title: to.meta.title || '未知页面',
            canRefresh: 'true'  // 标记可以尝试刷新权限
          }
        })
        return
      }
    }
    
    // 权限检查通过
    console.log('✅ 权限检查通过，允许访问')
    
    // 缓存结果
    cachePermissionCheck(cacheKey, true)
    
    // 清除权限错误
    authStore.clearPermissionError()
    
    LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING)
    next()
  } catch (error) {
    console.error('❌ 路由守卫错误:', error)
    LoadingManager.stopLoading(LOADING_KEYS.ROUTE_LOADING, { error: true })
    next(false)  // 取消导航
  }
})

// 路由后置守卫 - 设置页面标题
router.afterEach((to) => {
  if (to.meta.title) {
    document.title = `${to.meta.title} - 工单管理系统`
  } else {
    document.title = '工单管理系统'
  }
})

export default router


